<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 前端用户登录/注册接口
 *
 * @property User_mdl $users
 * @property Buy_lock_mdl $buyLock
 * @property Order_mdl $order 订单模型类
 * @property ApiOutput $apiOutput
 * @property Validation $validation 验证类
 * @property Tester_mdl $tester
 * @property School_mdl $school
 */
class Login extends CI_Controller {
	const E_SIGN = - 121; // 签名错误
	const E_CAPTCHA = - 122; // 验证码错误
	const E_UNREG = - 123; // 未注册(密码登录时)
	const E_PWD = - 124; // 密码错误
	const E_PHONE = - 125; // 手机号码格式不正确
	const E_LOCKED = - 126; // 离线取水授权绑定
	const E_HAS_UN_FINISH_ORDER = -127;// 用户有未完成的订单

	public function __construct() {
		parent::__construct ();
		$this->load->model ( 'User_mdl', 'users' );


	}
	/**
	 * 手机号码+短信验证码
	 */
	public function phone() {
		$input = $this->checkInput ( 'phone', 'captcha', 'phoneID' );
		$phone = $input ['phone'];
		$captcha = $input ['captcha'];
		$phoneID = $input ['phoneID'];
		// 非测试账号,需要验证手机验证码
		if (! $this->isTestPhone ( $phone, $captcha )) {
			$this->load->library ( 'PhoneCaptcha', NULL, 'captcha' );
			if (! $res=$this->captcha->check ( $phone, $captcha )) {
				$this->apiOutput->error ( '验证码错误或失效', self::E_CAPTCHA );
			}
			debug('test',$res);
		}

		// 检测该用户是否注册过
		$where = array ();
		$where ['phone'] = $phone;
		$user = $this->users->findOne ( $where );

		if (empty ( $user )) { // 如果没有注册过：执行注册
			$user = $this->users->create ();
			$user->phone = $phone;
			$user->phoneID = $phoneID;
			$user->nickname = substr_replace ( $phone, '*****', 3, 5 );
			$user->lastLoginPhoneID = $phoneID;
			if (! $user->reg ()) {
				// 保存到数据库失败:
				$this->apiOutput->errorSystem ();
			}
		}

		if($this->needLogin){
			$this->doLogin ( $user, $phoneID );
		}else{
			return $user;
		}
	}
	/**
	 * 手机号码+密码登录
	 */
	public function password() {

		$input = $this->checkInput ( 'phone', 'pwd', 'phoneID' );
		// 检测该用户是否注册过
		$where = array ();
		$where ['phone'] = $input ['phone'];
		$user = $this->users->findOne ( $where );
		if (empty ( $user )) {
			$this->apiOutput->error ( '您尚未注册!请通过短信验证码方式登录并注册!', self::E_UNREG );
		}
		if (! $user->checkPassword ( $input ['pwd'] )) {
			$this->apiOutput->error ( '密码错误', self::E_PWD );
		}
		$this->doLogin ( $user, $input ['phoneID'] );
	}

	/**
	 * 微信登陆
	 */
	public function wechat() {
		if( TRUE ){
			$this->apiOutput->error('抱歉,暂时不能使用微信登录!');
		}



		$input = $this->checkInput ( 'phoneID', 'wxOpenID', 'nickname', 'headImgUrl', 'wxUnionID' );
		// 检查是否注册过
		$where = array ();
		$where ['wxOpenID'] = $input ['wxOpenID'];
		$user = $this->users->findOne ( $where );
		if (empty ( $user )) { // 如果没有注册过,注册用户
			$user = $this->users->create ();
			$user->phoneID = $input ['phoneID'];
			$user->wxOpenID = $input ['wxOpenID'];
			$user->nickname = $input ['nickname'];
			$user->headImgUrl = $input ['headImgUrl'];
			$user->wxUnionID = $input ['wxUnionID'];
			$user->lastLoginPhoneID = $input ['phoneID'];
			if (! $user->reg ()) {
				$this->apiOutput->errorSystem ();
			}
		}

		$this->doLogin ( $user, $input ['phoneID'] );
	}
	/**
	 * 忘记密码
	 */
	public function forgot_pwd() {
		$this->needCheckSign = FALSE;
		$input = $this->checkInput('phone','captcha','pwd');

		$phone = $input['phone'];
		$captcha = $input['captcha'];
		$pwd = $input['pwd'];

		$this->load->library ( 'PhoneCaptcha', NULL, 'captcha' );
		if (! $this->captcha->check ( $phone, $captcha )) {
			$this->apiOutput->error ( '验证码错误或失效', self::E_CAPTCHA );
		}

		$where = array ();
		$where ['phone'] = $phone;
		$user = $this->users->findOne ( $where );
		if( empty($user) ){
			$this->apiOutput->error ( '该手机号码尚未注册!', self::E_UNREG );
		}

		if( $user->setPassword($pwd,TRUE) ){
			$this->apiOutput->put('msg', '密码设置成功!')->out();
		}else{
			$this->apiOutput->errorSystem();
		}


	}

	/**
	 * 执行登录
	 *
	 * @param UserORM $user
	 * @param string $phoneID
	 */
	private function doLogin($user, $phoneID) {
		// 是否测试账号
		if ($user->isTest == 1) {
			$testerData = $this->getTesterData ( $user );
			if (empty ( $testerData )) {
				$user->isTest = 0;
			} else {
				$this->apiOutput->put ( 'tester', $testerData );
			}
		}
		// 是否被其他手机离线授权绑定
		if (! empty ( $user->lockedPhoneID )) {
			if ($user->lockedPhoneID != $phoneID) {
				$this->apiOutput->error ( '您的账号已在其他手机离线授权,暂时不能更换手机登录', self::E_LOCKED );
			}
		}
		// 检查该用户是否有未完成订单
		$this->load->model('User_order_mdl','order');
// 		if ($this->order->checkHasUnfinishOrder( $user->id )) {
// 			$this->apiOutput->error ( '您的账号有未完成的订单,请稍后再试!', self::E_HAS_UN_FINISH_ORDER );
// 		}


		$user->afterLogin ( $phoneID );



		$this->apiOutput->put ( 'user', $user->getBaseInfo () )->out ();

	}


	private $needCheckSign = true;
	/**
	 * 获取输入参数
	 *
	 * @return array
	 */
	private function checkInput() {
		if( $this->needCheckSign ){
			// 登录注册前均需验证签名
			$this->load->library ( 'Validation', 'validation' );
			if (! $this->validation->checkSign ()) {
				$this->apiOutput->error ( '系统繁忙,请稍后再试![S]', self::E_SIGN );
			}
		}

		$mustExistsFields = func_get_args ();
		$input = check_input ( $_REQUEST, $mustExistsFields );
		if (! $input) {
			$this->apiOutput->errorInput ();
		}
		foreach ( $mustExistsFields as $field ) {
			switch ($field) {
				case 'phone' :
					if (empty ( $input ['phone'] )) {
						$this->apiOutput->error ( '手机号码格式不正确', self::E_PHONE );
					}
					break;
			}
		}
		return $input;
	}

	/**
	 * 获取测试人员数据
	 *
	 * @param UserORM $user
	 */
	private function getTesterData($user) {
		$this->load->model ( 'Tester_mdl', 'tester' );
		$where = array ();
		$where ['userID'] = $user->id;
		$props = $this->tester->getOne ( $where );
		if (time () > $props ['invalidTime']) {
			return NULL;
		}
		if( ! empty($props['schools']) ){
			$schoolIdList = explode(',', $props['schools']);
			$this->load->model ( 'School_mdl', 'school' );
			$props['schools'] = $this->school->getListByColValues('id,name', 'id', $schoolIdList);
		}else{
			$props['schools'] = array();
		}

		$rtn = array ();
		$rtn ['schools'] = $props['schools'];
		return $rtn;
	}

	/**
	 * 是否是测试的手机号码(主要给苹果公司审核人员测试)
	 *
	 * @param string $phone
	 * @param string $captcha
	 * @return boolean
	 */
	private function isTestPhone($phone, $captcha) {
		$phones = array (
				'18826121780',
// 				'13602417572',
				'13123456789'
		);
		return $captcha == 4738 && in_array ( $phone, $phones );
	}

	public $needLogin = TRUE;

	public function rongjun_test(){
		$this->apiOutput->setFormatHtml();
// 		$this->apiOutput->error($msg);
		$this->needLogin = FALSE;
		$this->needCheckSign = FALSE;
		$_GET['phoneID'] = 'test';
		$_POST['phoneID'] = 'test';
		$_REQUEST['phoneID'] = 'test';
		$user = $this->phone();
		$temp = array();
		$temp['error'] = 2;
		$temp['msg'] = '';
		$temp['hideMsg'] = TRUE;
		$temp['user'] =  $user->getBaseInfo();
		$this->load->view('rongjun/index',$temp);

	}






}
